<template>
  <a-row :gutter="24" class="search-row">
    <a-col :span="24">
      <x-card>
        <div slot="content" class="table-page-search-wrapper">
          <a-form layout="inline">
            <a-row :gutter="24">
              <a-col :span="6">
                <a-form-item label="数据来源" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-select
                    allow-clear
                    placeholder="请选择数据来源"
                    v-model="selectedCheckTypes"
                    mode="multiple"
                    @change="handleCheckTypeChange"
                    style="height: 40px; overflow-y: auto;">
                    <a-select-option value="全部">全部</a-select-option>
                    <a-select-option v-for="item in CheckTypeList" :key="item.id" :value="item.item">{{
                      item.item
                    }}</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="6">
                <a-form-item label="隐患单位" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-tree-select
                    allowClear
                    showSearch
                    style="width: 100%;"
                    tree-node-filter-prop="title"
                    v-model="DangerOrganizationName"
                    :treeData="QHSEOrganizationTree"
                    v-if="QHSEOrganizationTree.length"
                    @change="handleOrganizationSelectChange"
                    :defaultExpandAll="true"
                    :defaultExpandedKeys="defaultExpandedKeys"
                    :replaceFields="replaceFields"
                    ref="tree"
                    placeholder="请选择隐患单位"
                    :title="DangerOrganizationName"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="6">
                <a-form-item label="开始时间" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-date-picker
                    style="width: 100%"
                    format="YYYY-MM-DD"
                    @change="onChange1"
                    :style="{ width: '100%' }"
                    v-model="TimeOn" />
                </a-form-item>
              </a-col>
              <a-col :span="6">
                <a-form-item label="结束时间" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-date-picker
                    style="width: 100%"
                    format="YYYY-MM-DD"
                    @change="onChange2"
                    :style="{ width: '100%' }"
                    v-model="TimeEnd" />
                </a-form-item>
              </a-col>
              <a-col :span="6">
                <a-form-item label="隐患类别" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-tree-select
                    v-model="dangerCategory"
                    allowClear
                    showSearch
                    style="scroll: true"
                    tree-node-filter-prop="title"
                    v-if="DangerCategoryTree.length"
                    :treeData="DangerCategoryTree"
                    :defaultExpandAll="true"
                    :replaceFields="replaceFields"
                    @change="handleDangerTypeSelectChange"
                    placeholder="请选择隐患类别"
                    :title="dangerCategory"
                  >
                  </a-tree-select>
                </a-form-item>
              </a-col>
              <a-col :span="6">
                <a-form-item
                  label="作业专业"
                  :labelCol="labelCol"
                  :wrapperCol="wrapperCol"
                >
                  <a-select
                    allow-clear
                    placeholder="请选择作业专业"
                    v-model="selectedTypes"
                    mode="multiple"
                    @change="handleChange"
                    style="height: 40px; overflow-y: auto;"
                  >
                    <a-select-option value="全部">全部</a-select-option>
                    <a-select-option v-for="(item) in workSpecialData" :key="item.id" :value="item.specialty">{{ item.specialty }}</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :span="6">
                <a-form-item label="检查单位" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <a-tree-select
                    allowClear
                    showSearch
                    style="width: 100%;"
                    tree-node-filter-prop="title"
                    v-model="checkOrganizationName"
                    :treeData="QHSEOrganizationTree1"
                    v-if="QHSEOrganizationTree1.length"
                    @change="handleCheckOrganizationSelectChange"
                    :defaultExpandAll="true"
                    :defaultExpandedKeys="defaultExpandedKeys"
                    :replaceFields="replaceFields"
                    ref="tree"
                    placeholder="请选择检查单位"
                    :title="checkOrganizationName"
                  />
                </a-form-item>
              </a-col>
              <a-col :span="6" style="margin-bottom: 3px;">
                <a-button type="primary" @click="handleClick" :loading="loading2">{{ loading2 ? '查询中...' : '查询' }}</a-button>
                <a-button style="margin-left: 8px" @click="reset">重置</a-button>
                <a-button type="primary" @click="handleExport" :loading="batchExportLoading"><a-icon type="export"/>导出数据</a-button>
              </a-col>
            </a-row>
          </a-form>
        </div>
      </x-card>
      <a-row :gutter="48" class="search-row">
        <a-col :span="24">
          <a-divider orientation="left" style="font-weight: bold; margin-bottom: -2px;margin-top: -2px"> 隐患类别分析
          </a-divider>
          <a-card style="overflow-y: hidden" :style="{ height: cardHeight }">
            <!-- <a-progress
              class="prog"
              type="circle"
              :strokeWidth="10"
              :percent="percent"
              :width="200"
              v-if="loading"
            /> -->
            <a-row style="width: 100%; height: 800px;">
              <a-col :span="24">
                <div id="bar-chart-container5" style="width: 100%; height: 800px;"></div>
              </a-col>
            </a-row>
            <a-row style="width: 100%; height: 600px;">
              <a-col :span="24">
                <div id="bar-chart-container1" style="width: 100%; height: 600px;"></div>
              </a-col>
            </a-row>
            <a-row style="width: 100%; height: 600px;">
              <a-col :span="12">
                <div id="bar-chart-container2" style="width: 100%; height: 600px;"></div>
              </a-col>
              <a-col :span="12">
                <div id="bar-chart-container3" style="width: 100%; height: 600px;"></div>
              </a-col>
            </a-row>
            <!-- <a-row style="width: 100%; height: 800px;" :style="{ visibility: !loading ? 'visible' : 'hidden' }"></a-row> -->
            <a-row style="width: 100%; height: 800px;">
              <a-col :span="24">
                <div id="bar-chart-container4" style="width: 100%; height: 800px;"></div>
              </a-col>
            </a-row>
          </a-card>
        </a-col>
      </a-row>
    </a-col>
  </a-row>
</template>
    <script>
    import { STable, XCard, XDown } from '@/components'
    import { getQHSEOrganizationTree } from '@/api/modular/system/QHSEOrganization'
    import { getQHSECheckTypeList, getDangerCategoryTree } from '@/api/modular/system/QHSEHazardQuery'
    import { getWorkSpecialtyList } from '@/api/modular/system/violationManage'
    import {
      getTypeAnalysis,
      getDanCauseAnalysis,
      getDanDirectDepartmentAnalysis,
      getHSEAnalysis,
      getDanCateAnalysis
     } from '@/api/modular/system/QSHEDancategoryAna'
    import * as echarts from 'echarts'
    import moment from 'moment'
    import { mapGetters } from 'vuex'
    import * as XLSX from 'xlsx'
    export default {
      components: {
        XDown,
        XCard,
        STable
      },
      data() {
        return {
          labelCol: {
            xs: { span: 24 },
            sm: { span: 6 }
          },
          wrapperCol: {
            xs: { span: 24 },
            sm: { span: 16 }
          },
          // 获取参数
          queryParam: {
            TimeOn: moment(new Date()).subtract(1, 'months').format('YYYY-MM-DD'),
            TimeEnd: moment(new Date()).format('YYYY-MM-DD') + 'T' + moment().format('23:59:59')
          },
          // 导出参数
          exportParam: {},
          selectedPeriod: '周',
          TimeOn: moment(new Date(), 'YYYY-MM-DD').subtract(1, 'months'),
          TimeEnd: moment(new Date(), 'YYYY-MM-DD'),
          showRadio: false,
          selectedTypes: [],
          tableData1: [],
          tableData2: [],
          tableData3: [],
          tableData4: [],
          tableData5: [],
          workSpecialData: [],
          QHSEOrganizationTree: [],
          QHSEOrganizationTree1: [],
          checkOrganizationName: '',
          DangerOrganizationName: '',
          DangerCategoryTree: [],
          selectCheckTypes: [],
          CheckTypeList: [], // 数据来源
          selectedCheckTypes: [],
          defaultExpandedKeys: [],
          loading2: false,
          chart: false,
          cardHeight: '400px',
          dangerCategory: '',
          batchExportLoading: false,
          replaceFields: {
            children: 'children',
            title: 'title',
            key: 'workflowId',
            value: 'id',
            parentId: 'parentId'
          },
          loading: false,
          percent: 0,
          secondOraName: {
          id: ''
        }
        }
      },
      watch: {
        percent(newVal) {
          if (newVal === 100) {
            setTimeout(() => {
              this.percent = 1
              // this.loading = false
              this.loading2 = false
            }, 500)
          }
        }
      },
      computed: {
      ...mapGetters(['userInfo'])
      },
      created() {
        this.getQHSEOrganizationTree()
        this.getQHSECheckTypeList()
        this.getWorkSpecialtyList()
        this.getDangerCategoryTree()
      },
      methods: {
        exportWholePageToExcel() {
      const tablesData = [
        { data: this.tableData5, name: '隐患类别' },
        { data: this.tableData1, name: '隐患级别' },
        { data: this.tableData2, name: '归属直线部门' },
        { data: this.tableData3, name: '隐患原因' },
        { data: this.tableData4, name: '体系要素' }
      ]
      console.log(tablesData)
       // 创建一个工作簿
      const workbook = XLSX.utils.book_new()
     // 遍历每个表格的数据，将其转换为对应的工作表并添加到工作簿
        tablesData.forEach(({ data, name }, index) => {
          // 确保数据是一个二维数组
          if (Array.isArray(data) || Array.isArray(data[0])) {
            // 将每个数组转换为对应的工作表
            const worksheet = XLSX.utils.json_to_sheet(data)
            // 将工作表添加到工作簿，并使用表格名称作为工作表名称
            XLSX.utils.book_append_sheet(workbook, worksheet, name)
          } else {
            console.error(`Data for table ${name} is not a valid two-dimensional array`)
          }
        })
        // 生成Excel文件
        XLSX.writeFile(workbook, '隐患类别分析.xlsx')
        this.batchExportLoading = false
      },
      handleExport() {
        this.batchExportLoading = true
        this.exportWholePageToExcel()
      },
        renderChart(data, containerId, chartType) {
      const barChartContainer = document.getElementById(containerId)
      const barChart = echarts.init(barChartContainer)
      const barChartData = data.map(item => ({
        value: item.value,
        name: item.name
      }))
        const barChartOptions = {
        title: {
          text: '',
          textStyle: {
            fontWeight: 'bold',
            fontSize: 20
          },
          left: 'center' // 标题水平居中
        },
        grid: {
          containLabel: true,
          top: 60
        },
        xAxis: {
          type: 'category',
          data: null,
          axisLabel: {
            interval: 1
          }
        },
        yAxis: {
          type: chartType === 'vertical' ? 'value' : 'category',
          data: null
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        series: [
          {
            type: 'bar',
            data: barChartData,
            barWidth: '40%',
            label: {
              show: true, // 显示标签
              position: 'top',
              formatter: function (params) {
                // 只显示偶数索引的标签
                return params.dataIndex % 2 === 0 ? params.value : ''
              }
            }
          }
        ]
      }
      if (containerId === 'bar-chart-container1') {
         barChartOptions.title.text = '隐患级别'
         barChartOptions.yAxis.type = 'value'
         barChartOptions.xAxis.data = barChartData.map(item => item.name)
         barChartOptions.xAxis.axisLabel = {
           formatter: function (value) {
             return value.split('').join('\n') // 在每个字符之间添加换行符
           },
           fontSize: 14 // 设置较大的字体大小
         }
       } else if (containerId === 'bar-chart-container4') {
        barChartOptions.title.text = '体系要素'
          barChartOptions.yAxis.type = 'value'
          barChartOptions.xAxis.data = barChartData.map(item => item.name)
          barChartOptions.xAxis.axisLabel = {
            formatter: function (value) {
              return value.split('').join('\n') // 在每个字符之间添加换行符
            },
            fontSize: 14 // 设置较大的字体大小
          }
       } else if (containerId === 'bar-chart-container3') {
        barChartOptions.title.text = '隐患原因'
          barChartOptions.yAxis.type = 'value'
          barChartOptions.xAxis.data = barChartData.map(item => item.name)
          barChartOptions.xAxis.axisLabel = {
            formatter: function (value) {
              return value.split('').join('\n') // 在每个字符之间添加换行符
            },
            fontSize: 14 // 设置较大的字体大小
          }
       } else if (containerId === 'bar-chart-container2') {
        barChartOptions.title.text = '归属直线部门'
          barChartOptions.yAxis.type = 'value'
          barChartOptions.xAxis.data = barChartData.map(item => item.name)
          barChartOptions.xAxis.axisLabel = {
            formatter: function (value) {
              return value.split('').join('\n') // 在每个字符之间添加换行符
            },
            fontSize: 14 // 设置较大的字体大小
          }
       } else if (containerId === 'bar-chart-container5') {
        barChartOptions.title.text = '隐患类别'
          barChartOptions.yAxis.type = 'value'
          barChartOptions.xAxis.data = barChartData.map(item => item.name)
          barChartOptions.xAxis.axisLabel = {
            formatter: function (value) {
              return value.match(/.{1,7}/g).join('\n') // 每七个字符添加换行符
            },
            fontSize: 14 // 设置较大的字体大小
          }
       }
        if (barChartData.length > 0) {
          barChart.setOption(barChartOptions)
        }
      },
      handleChange(value) {
        if (value.includes('全部')) {
          // 选中了全部选项，将所有选项都添加到 selectedTypes 中
          this.selectedTypes = this.workSpecialData.map((item) => item.specialty)
        }
        this.queryParam.WorkSpeciality = this.selectedTypes.map((option) => option.toString())
      },
        handleClick() {
          if (this.queryParam.CheckType.length === 0 || !this.queryParam.DangerOrganizationName || !this.queryParam.dangerCategory || this.queryParam.WorkSpeciality.length === 0 || !this.TimeOn || !this.TimeEnd) {
            this.$message.warning('请填写完整的查询条件')
          } else {
            this.loading2 = true
            // this.loading = true
            this.percent = 1
            this.loadData1()
            this.loadData2()
            this.loadData3()
            this.loadData4()
            this.loadData5()
            this.chart = true
            this.showRadio = true
            this.cardHeight = 'auto'
            // console.log(this.queryParam)
          }
        },
        async handleCheckTypeChange(value) {
          if (value.includes('全部')) {
            // 选中了全部选项，将所有选项都添加到 selectedCheckTypes 中
            this.selectedCheckTypes = this.CheckTypeList.map(item => item.item)
          }
          this.queryParam.CheckType = this.selectedCheckTypes.map(option => option.toString())
        },
        loadData1() {
          getTypeAnalysis(this.queryParam)
            .then(res => {
              this.tableData1 = res.data
              this.renderChart(res.data, 'bar-chart-container1', 'vertical')
              this.percent += 24
            })
            .catch(error => {
              // 处理请求错误
              console.error(error)
              this.loading2 = false
              // 显示错误信息
              this.$message.error('获取数据失败')
            })
        },
        loadData3() {
          getDanDirectDepartmentAnalysis(this.queryParam)
            .then(res => {
              this.tableData2 = res.data
              this.renderChart(res.data, 'bar-chart-container2', 'vertical')
              this.percent += 25
            })
            .catch(error => {
              // 处理请求错误
              console.error(error)
              // 显示错误信息
              this.$message.error('获取数据失败')
              this.loading2 = false
            })
        },
        loadData2() {
          getDanCauseAnalysis(this.queryParam)
            .then(res => {
              this.tableData3 = res.data
              this.renderChart(res.data, 'bar-chart-container3', 'vertical')
              this.percent += 25
            })
            .catch(error => {
              // 处理请求错误
              console.error(error)
              this.loading2 = false
              // 显示错误信息
              this.$message.error('获取数据失败')
            })
        },
        loadData4() {
          getHSEAnalysis(this.queryParam)
          .then(res => {
            this.tableData4 = res.data
            this.renderChart(res.data, 'bar-chart-container4', 'vertical')
            this.percent += 20
          })
          .catch(error => {
            // 处理请求错误
            console.error(error)
            this.loading2 = false
            // 显示错误信息
            this.$message.error('获取数据失败')
          })
      },
      loadData5() {
          getDanCateAnalysis(this.queryParam)
          .then(res => {
            this.tableData5 = res.data
            this.renderChart(res.data, 'bar-chart-container5', 'vertical')
            this.percent += 5
            // this.loading2 = false
          })
          .catch(error => {
            // 处理请求错误
            console.error(error)
            this.loading2 = false
            // 显示错误信息
            this.$message.error('获取数据失败')
          })
      },
       onChange1(date, dateString) {
        // console.log(dateString, date)
        if (this.queryParam.TimeEnd && dateString) {
          if (dateString > this.queryParam.TimeEnd) {
            this.$message.error('开始时间不能晚于结束时间')
            this.TimeEnd = moment(new Date(), 'YYYY-MM-DD')
            this.TimeOn = moment(new Date(), 'YYYY-MM-DD').subtract(1, 'months')
            this.queryParam.TimeOn = moment(new Date()).subtract(1, 'months').format('YYYY-MM-DD')
            this.queryParam.TimeEnd = moment(new Date()).format('YYYY-MM-DD') + 'T' + moment().format('23:59:59')
          } else {
            this.queryParam.TimeOn = dateString
          }
        } else {
          this.queryParam.TimeOn = dateString
        }
      },
        onChange2(date, dateString) {
          if (this.queryParam.TimeOn && dateString) {
            if (this.queryParam.TimeOn > dateString) {
              this.$message.error('开始时间不能晚于结束时间')
              this.TimeEnd = moment(new Date(), 'YYYY-MM-DD')
              this.TimeOn = moment(new Date(), 'YYYY-MM-DD').subtract(1, 'months')
              this.queryParam.TimeOn = moment(new Date()).subtract(1, 'months').format('YYYY-MM-DD')
              this.queryParam.TimeEnd = moment(new Date()).format('YYYY-MM-DD') + 'T' + moment().format('23:59:59')
            } else {
              this.queryParam.TimeEnd = dateString + 'T' + moment().format('23:59:59')
            }
          } else {
            this.queryParam.TimeEnd = dateString + 'T' + moment().format('23:59:59')
          }
        },
        // 更改隐患单位
        handleOrganizationSelectChange(val, opt, extra) {
          if (extra.triggerNode === undefined) {
            this.queryParam.DangerOrganizationName = null
            this.queryParam.DangerOrganizationId = null
          } else {
            const option = extra.triggerNode._props.title
            this.queryParam.DangerOrganizationName = option
            this.queryParam.DangerOrganizationId = extra.triggerNode._props.value
            this.DangerOrganizationName = this.queryParam.DangerOrganizationName
          }
        },
               // 更改检查单位
    handleCheckOrganizationSelectChange(val, opt, extra) {
          if (extra.triggerNode === undefined) {
            this.queryParam.checkOrganizationName = null
            this.queryParam.checkOrganizationId = null
          } else {
            const option = extra.triggerNode._props.title
            this.queryParam.checkOrganizationName = option
            this.queryParam.checkOrganizationId = extra.triggerNode._props.value
            this.checkOrganizationName = this.queryParam.checkOrganizationName
          }
        },
        onChangeCheckData(value, label, extra) {
          // console.log(value, label, extra)
          if (extra.triggerNode === undefined) {
            this.queryParam.CheckOrganizationName = null
            this.queryParam.CheckOrganizationId = null
          } else {
            const option = extra.triggerNode._props.title
            this.queryParam.CheckOrganizationName = option
            this.queryParam.CheckOrganizationId = extra.triggerNode._props.value
          }
        },
        getQHSEOrganizationTree () {
          this.secondOraName.id = this.userInfo.secondOrganizationName
          getQHSEOrganizationTree(Object.assign(this.secondOraName)).then(res => {
            // console.log('tree:', res.data)
            this.treeLoading = false
            if (!res.success) {
              return
            }
            this.QHSEOrganizationTree = res.data
            if (res.data.length === 0) {
              this.secondOraName.id = '机关总部'
              getQHSEOrganizationTree(Object.assign(this.secondOraName)).then(res => {
                this.QHSEOrganizationTree = res.data
                this.queryParam.DangerOrganizationName = res.data[0].title
                this.queryParam.DangerOrganizationId = res.data[0].id
                this.DangerOrganizationName = this.queryParam.DangerOrganizationName
              })
            } else {
              this.queryParam.DangerOrganizationName = res.data[0].title
              this.queryParam.DangerOrganizationId = res.data[0].id
              this.DangerOrganizationName = this.queryParam.DangerOrganizationName
            }
            })
            this.secondOraName.id = '安检院'
          getQHSEOrganizationTree(Object.assign(this.secondOraName)).then(res => {
            // console.log('tree:', res.data)
            this.treeLoading = false
            if (!res.success) {
              return
            }
            this.QHSEOrganizationTree1 = res.data
            this.queryParam.checkOrganizationName = res.data[0].title
            this.queryParam.checkOrganizationId = res.data[0].id
            this.checkOrganizationName = this.queryParam.checkOrganizationName
        })
        },
        getQHSECheckTypeList(text) {
          getQHSECheckTypeList().then((res) => {
            this.CheckTypeList = res.data // 将后端返回的数据赋值给 CheckTypeList
            const select = '全部'
            this.handleCheckTypeChange(select)
          })
        },
        getWorkSpecialtyList () {
          getWorkSpecialtyList(Object.assign(this.queryParam)).then(res => {
            // console.log(res.data)
            this.treeLoading = false
            if (!res.success) {
              return
            }
            this.workSpecialData = res.data
            const select = '全部'
            this.handleChange(select)
          })
        },
        handleDangerTypeSelectChange(val, opt, extra) {
          if (extra.triggerNode === undefined) {
            this.queryParam.dangerCategory = null
            // this.dangerCategory = this.queryParam.dangerCategory
          } else {
            const option = extra.triggerNode._props.title
            this.queryParam.dangerCategory = option
            this.dangerCategory = this.queryParam.dangerCategory
          }
        },
    // 类别
    getDangerCategoryTree() {
      getDangerCategoryTree().then((res) => {
        this.formLoading = false
        if (!res.success) {
          this.DangerCategoryTree = []
          return
       }
        this.DangerCategoryTree = res.data
        // console.log(res.data)
        this.queryParam.dangerCategory = res.data[0].title
        this.dangerCategory = this.queryParam.dangerCategory
        console.log('this.dangerCategory', this.dangerCategory)
      }).catch((error) => {
        console.error(error) // 打印错误信息
      })
  },
        reset() {
        this.queryParam = {
          TimeOn: moment(new Date()).subtract(1, 'months').format('YYYY-MM-DD'),
          TimeEnd: moment(new Date()).format('YYYY-MM-DD') + 'T' + moment().format('23:59:59')
        }
        this.TimeEnd = moment(new Date(), 'YYYY-MM-DD')
        this.TimeOn = moment(new Date(), 'YYYY-MM-DD').subtract(1, 'months')
          this.selectedCheckTypes = []
          this.dangerCategory = []
          this.WorkSpeciality = []
          this.selectedTypes = []
        }
      }
    }
    </script>
    <style lang="less" scoped>
    .table-operator {
      margin-bottom: 18px;
    }

    button {
      margin-right: 8px;
    }

    .search-row {
      display: flex;
      align-items: center;
    }

    .search-buttons {
      display: flex;
      justify-content: flex-end;
      margin-bottom: 10px;
    }

    .chart-container {
      margin-top: 20px;
      /* 调整顶部边距 */
      display: flex;
      flex-direction: column;
      justify-content: flex-start;
      align-items: center;
    }
    .ellipsis-text {
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
      text-align: left;
    }
    .prog {
      position: relative;
      top: 90px;
      left: 42%;
    }
    /deep/.ant-progress-text {
      font-size: 2rem;
    }
    /deep/.ant-progress-circle-path {
      animation: rotate 3s linear infinite;
      transform-origin: center center;
    }

    @keyframes rotate {
      0% {
        transform: rotate(0deg);
      }
      100% {
        transform: rotate(360deg);
      }
    }
    </style>
